import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	message,
	Tag,
	Space,
	TreeSelect,
	Cascader,
} from 'antd'
import React, {useState, useEffect, memo, useRef} from 'react'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import CustomTable from '@/components/Table'
import {
	viewRenewal,
	getTablePage,
	addRenewal,
	editRenewal,
	autoRenewalExport,
	getIsProcessOpen,
	renewalProcessAdd,
	renewalAuditFlow,
	getNodePropertys,
} from '@/service/carMessage/renewal'
import {getBusinessCode} from '@/service/carMessage/common'
import {getCompany} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'
import {getAllCitys} from '@/service/common'
import {
	renewalType,
	carStatus,
	operationType,
	carLicenseStatus,
} from '../../dict'
import {twoDecimalPattern} from '@/utils/common/validator'
import {getPublicDownloadUrl} from '@/service/common/upload'
import {downloadImage} from '@/service/common/download'

import 'moment/locale/zh-cn'
import Examine from '@/components/Examine'

const {Panel} = Collapse

const add = memo((props: any) => {
	const [type, setType] = useState<string>()
	// 记录列表
	const [recordList, setRecordList] = useState([])
	const [recordLoading, setRecordLoading] = useState(false)
	const [form] = Form.useForm()
	const [otherParams, setOtherParams] = useState<any>()
	const [file, setFile] = useState<any>()
	const [renewalId, setRenewalId] = useState<any>()
	const [selectRenewalType, setSelectRenewalType] = useState<any>()
	const [selectRenewalName, setSelectRenewalName] = useState<string>('')
	const [recordForm] = Form.useForm()
	const [orgSource, setOrgSource] = useState<any>([])
	const [citysList, setCitysList] = useState([])
	const [btnLoading, setBtnLoading] = useState<boolean>(false)
	const examineRef = useRef<any>(null)
	// 流程id
	const [instanceId, setInstanceId] = useState<string>()
	const [processOpen, setProcessOpen] = useState<number>(0)
	const [nodePropertys, setNodePropertys] = useState<any>({})
	const [total, setTotal] = useState(0)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	// 初始化-流程是否激活
	const getIsProcessOpenFun = () => {
		getIsProcessOpen({businessType: 1})
			.then((res: any) => {
				if (res?.success) {
					setProcessOpen(() => res?.data)
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	const getNodePropertsyFun = () => {
		getNodePropertys({businessType: 1, instanceId})
			.then((res: any) => {
				if (res?.success) {
					setNodePropertys(res?.data)
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	useEffect(() => {
		if (instanceId) {
			getNodePropertsyFun()
		}
	}, [instanceId])

	// 初始化-获取车辆证照补办编号
	const getTargetCode = () => {
		getBusinessCode({moduleName: 'renewal'}).then((res: any) => {
			if (res?.success) {
				form.setFieldsValue({renewalNo: res?.data})
			}
		})
	}

	// 数据自动生成附件数据
	const getRecordList = () => {
		const submitForm = form.getFieldsValue()

		setSelectRenewalType(submitForm?.renewalType)
		if (submitForm?.renewalType) {
			setRecordLoading(true)
			getTablePage(submitForm?.renewalType, {
				...params,
				companyId: submitForm?.orgId,
				cityId: submitForm?.city ? submitForm?.city[1] : '',
			})
				.then((res: any) => {
					if (res?.success) {
						setRecordList(res?.data?.records)
						setRecordLoading(false)
						setTotal(res.data.total)
					}
				})
				.catch((err: any) => {
					message.error(err)
					setRecordLoading(false)
				})
		}
	}
	useEffect(() => {
		getRecordList()
	}, [params])

	// 初始化-附件列表
	const getFileList = (ids: any) => {
		getPublicDownloadUrl(ids).then((res: any) => {
			if (res?.success) {
				const list = res?.data
				setFile(() => [...list][0])
			}
		})
	}

	// 初始化-详情数据
	const getView = (id: string) => {
		viewRenewal({id}).then((res: any) => {
			if (res?.success) {
				setInstanceId(res?.data?.instanceId)
				form.setFieldsValue({
					...res?.data,
					city: [res?.data?.parentCityId, res?.data?.cityId],
					renewalTime: moment(res?.data?.renewalTime).format(
						'YYYY-MM-DD HH:mm:ss',
					),
				})
				setOtherParams({
					...otherParams,
					parentCityId: res?.data?.parentCityId,
					cityId: res?.data?.cityId,
					cityName: res?.data?.cityName,
					fileKey: res?.data?.fileKey,
				})
				setParams({
					current: 1,
					size: 10,
				})
				getRecordList()
				const label = [...renewalType].filter(
					(item: any) => item?.key === res?.data?.renewalType,
				)[0]?.label
				setSelectRenewalName(() => label)
				getFileList([res?.data?.fileKey])
			}
		})
	}
	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
	}

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}

	useEffect(() => {
		onOrgFun()
		getCitysFun()
	}, [props?.user?.orgId])

	const onRenewalTypeChange = (value: number, option: any) => {
		setFile(() => null)
		setSelectRenewalName(() => option?.label)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onRenewalOrgIdChange = () => {
		setFile(() => null)
		setParams({
			current: 1,
			size: 10,
		})
		getRecordList()
	}

	// 根据路由判断当前页面状态
	useEffect(() => {
		const {id} = props.location.query
		if (id) {
			getView(id)
			setRenewalId(id)
		}
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			getIsProcessOpenFun()
			setType('add')
			form.setFieldsValue({
				renewalApply: props?.user?.userName,
				renewalTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
			})
			setOtherParams({
				...otherParams,
				applicantId: props?.user?.userId,
			})
			getTargetCode()
		} else if (hrefs.includes('edit')) {
			getIsProcessOpenFun()
			setType('edit')
		} else {
			setType('process')
		}
	}, [])
	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)

	/**
	 * desc: 文件下载 导出结果处理  type:文件类型 zip .xls .xlsx ...
	 */

	const getAutoRenewalExport = () => {
		const formData = form.getFieldsValue()
		if (formData?.renewalType == null || undefined) {
			message.error('请选择补办类型')
		} else {
			setBtnLoading(() => true)
			autoRenewalExport({
				renewalType: formData?.renewalType,
				companyId: formData?.orgId,
				cityId: formData?.city ? formData?.city[1] : null,
			})
				.then((res) => {
					if (res?.success) {
						getFileList([res?.data.id])
						message.success(res?.msg)
					}
					setBtnLoading(() => false)
				})
				.catch((err) => {
					setBtnLoading(() => false)
					message.error(err)
				})
		}
	}
	// 处理保存
	const onSubmit = async () => {
		const submitForm = await form.validateFields()
		if (!file) {
			message.error('请重新生成附件!')
		} else {
			let request
			const queryData = {
				...submitForm,
				...otherParams,
				fileKey: file.id,
			}
			if (renewalId) {
				queryData.id = renewalId
			}
			if (processOpen === 1) {
				// 流程开启时发起流程
				request = renewalProcessAdd(queryData)
			} else if (!renewalId) {
				// 新增
				request = addRenewal(queryData)
			} else {
				// 编辑
				request = editRenewal(queryData)
			}
			request
				.then((res) => {
					if (res?.success) {
						message.success(res?.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}

	// 城市变化
	const onCitysChange = (value: any, selectedOptions: any) => {
		if (value) {
			setFile(() => null)
			setParams({
				current: 1,
				size: 10,
			})
			getRecordList()
			setOtherParams({
				...otherParams,
				parentCityId: selectedOptions[0].id,
				cityId: selectedOptions[1].id,
				cityName: selectedOptions[1].name,
			})
		}
	}

	/** 审核 */
	const onCompleteTask = async (pass: string) => {
		const examineData = await examineRef.current.getData()
		if (examineData?.url) {
			const flowParams = {
				message: examineData?.message,
				businessId: props.location.query?.id,
				instanceId,
				pass,
				attachmentList: examineData?.url?.split(','),
			}
			if (pass === '3') {
				flowParams.message = JSON.stringify(examineData)
			}
			renewalAuditFlow(flowParams)
				.then((res: {msg: string; success: boolean}) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					} 
				})
				.catch((err: any) => {
					message.error(err)
				})
		} else {
			message.warning('请上传附件')
		}
	}

	return (
		<div className={styles.admittanceAdd}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				{instanceId && (type === 'view' || type === 'process') ? (
					<Examine
						ref={examineRef}
						examineType={type === 'process'}
						orgId={props?.user?.orgId}
						processInstanceId={instanceId}
						required
					/>
				) : (
					''
				)}
				<Collapse
					defaultActiveKey={['1', '2']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '120px'}}
							labelAlign="right"
							labelWrap
							initialValues={{remember: true}}
							autoComplete="off"
							disabled={type === 'view' || type === 'process'}>
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="证照申请单号"
										name="renewalNo"
										rules={[{required: true}]}>
										<Input placeholder="请输入" disabled />
									</Form.Item>
								</Col>

								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="申请人"
										name="renewalApply"
										rules={[{required: true}]}>
										<Input placeholder="请输入" disabled />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="申请时间"
										name="renewalTime"
										rules={[{required: true}]}>
										<Input placeholder="请输入" disabled />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="补办预估金额"
										name="renewalFee"
										getValueFromEvent={
											(event: any) =>
												event.target.value.replace(
													/^(-)*(\d+)\.(\d\d).*$/,
													'$1$2.$3',
												) // 只能输入两位小数
										}
										rules={[
											{
												required: true,
												pattern: twoDecimalPattern, // 只能输入数字跟小数点 两位小数
												message:
													'请输入正确的补办预估金额',
											},
										]}>
										<Input placeholder="请输入" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="补办类型"
										name="renewalType"
										rules={[{required: true}]}>
										<Select
											placeholder="请选择"
											fieldNames={{
												value: 'key',
												label: 'label',
											}}
											options={[...renewalType]}
											onChange={onRenewalTypeChange}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="所属公司"
										name="orgId"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择"
											allowClear
											treeDefaultExpandAll
											fieldNames={{
												label: 'name',
												value: 'id',
											}}
											treeDataSimpleMode
											treeData={[...orgSource]}
											onChange={onRenewalOrgIdChange}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="所属城市"
										name="city"
										rules={[
											{required: true, message: '请选择'},
										]}>
										<Cascader
											fieldNames={{
												label: 'name',
												value: 'id',
												children: 'cityInfoList',
											}}
											options={citysList}
											placeholder="请选择"
											onChange={onCitysChange}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
					<Panel header={customizeHeader('数据自动生成附件')} key="2">
						{type !== 'process' ? (
							<div className="btnlist">
								<Space size={12}>
									<Button
										ghost
										type="primary"
										size="small"
										loading={btnLoading}
										onClick={() => {
											getAutoRenewalExport()
										}}>
										自动生成附件
									</Button>
								</Space>
							</div>
						) : (
							''
						)}
						<Form
							form={recordForm}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '80px'}}
							labelAlign="right"
							labelWrap
							initialValues={{remember: true}}
							autoComplete="off">
							<Row gutter={12}>
								<Col sm={{span: 24}}>
									<CustomTable
										columns={[
											{
												title: '车辆ID',
												dataIndex: 'carId',
												width: 150,
												align: 'center',
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '车牌号',
												dataIndex: 'carPlateNo',
												align: 'center',
												width: 150,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '品牌车系车型',
												dataIndex: 'carBrandSeries',
												align: 'center',
												width: 250,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '车辆状态',
												dataIndex: 'carStatus',
												width: 150,
												align: 'center',
												render: (text: number) => (
													<>
														{carStatus?.map(
															(item: {
																key: number
																label: string
															}) => {
																if (
																	item?.key ===
																	text
																) {
																	return (
																		<Tag
																			color="processing"
																			key={
																				item?.key
																			}>
																			{
																				item?.label
																			}
																		</Tag>
																	)
																}
																return ''
															},
														)}
													</>
												),
											},
											{
												title: '持有方',
												dataIndex: 'holderName',
												align: 'center',
												width: 150,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '所属公司',
												dataIndex: 'companyName',
												align: 'center',
												width: 150,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '所有人',
												dataIndex: 'ownerName',
												align: 'center',
												width: 150,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '城市',
												dataIndex: 'cityName',
												align: 'center',
												width: 150,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
											{
												title: '运营分类',
												dataIndex: 'selfManaged',
												align: 'center',
												width: 150,
												render: (text: number) => (
													<>
														{operationType?.map(
															(item: {
																key: number
																label: string
															}) => {
																if (
																	item?.key ===
																	text
																) {
																	return (
																		<Tag
																			color="processing"
																			key={
																				item?.key
																			}>
																			{
																				item?.label
																			}
																		</Tag>
																	)
																}
																return ''
															},
														)}
													</>
												),
											},
											{
												title: () => {
													if (!selectRenewalType) {
														return '行驶证'
													}
													return renewalType?.filter(
														(item: any) =>
															item.key ===
															selectRenewalType,
													)[0]?.label
												},
												dataIndex: 'renewalStatus',
												align: 'center',
												width: 150,
												render: (text: number) => (
													<>
														{carLicenseStatus?.map(
															(item: {
																key: number
																label: string
															}) => {
																if (
																	item?.key ===
																	text
																) {
																	return (
																		<Tag
																			color="processing"
																			key={
																				item?.key
																			}>
																			{
																				item?.label
																			}
																		</Tag>
																	)
																}
																return ''
															},
														)}
													</>
												),
											},
											{
												title: '最近盘点时间',
												dataIndex: 'inventoryTime',
												align: 'center',
												width: 250,
												render: (text: string) => (
													<span>{text || '--'}</span>
												),
											},
										]}
										loading={recordLoading}
										dataSource={recordList}
										params={params}
										pagination
										total={total}
										callback={(pagination: any) => {
											setParams(pagination)
										}}
									/>
								</Col>
								{file ? (
									<Col sm={{span: 24}}>
										<div className="files">
											附件：
											<Button
												type="primary"
												size="small"
												className="downOrupload"
												onClick={() => {
													downloadImage(
														file.filename,
														file.url,
													)
												}}>
												{total} 辆车
												{selectRenewalName}补办明细
											</Button>
										</div>
									</Col>
								) : null}
							</Row>
						</Form>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					{type === 'add' || type === 'edit' ? (
						<>
							<Button type="primary" onClick={onSubmit}>
								保存
							</Button>
						</>
					) : (
						''
					)}
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						取消
					</Button>
					{type === 'process' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => {
									onCompleteTask('1')
								}}>
								同意
							</Button>
							{Object.keys(nodePropertys).length ? (
								<Button
									onClick={() => {
										onCompleteTask('2')
									}}>
									驳回
								</Button>
							) : (
								''
							)}

							<Button
								onClick={() => {
									onCompleteTask('3')
								}}>
								拒绝
							</Button>
						</>
					) : (
						''
					)}
				</div>
			</div>
		</div>
	)
})
export default connect(({user}: any) => ({user, global}))(add)
